package codingPractice.huawei;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Test1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            String[] express = new String[n];
            sc.nextLine();
            for(int i=0;i<n;i++) {
                express[i] = sc.nextLine();
            }
//            sc.nextLine();
            Map<String, String> kv = new HashMap<>();
            for(int i=0;i<m;i++) {
                String key = sc.next();
                String value = sc.next();
                kv.put(key, value);
            }

            for(String expression : express) {
                if (evaluateExpression(expression, kv)) {
                    System.out.println(0);
                } else {
                    System.out.println(1);
                }
            }
        }
    }

    private static boolean evaluateExpression(String expression, Map<String, String> data) {
        for(Map.Entry<String, String> entry : data.entrySet()) {
            String field = entry.getKey();
            String value = entry.getValue();
            expression = expression.replaceAll(field + "='(.*?)'", "'" + value + "'='$1'");
        }

        return evaluateBooleanExpression(expression, data);
    }


    private static boolean evaluateBooleanExpression(String expression, Map<String, String> data) {
        if (expression.contains("(")) {
            int openIndex = expression.lastIndexOf('(');
            int closeIndex = expression.indexOf(')', openIndex);
            String innerExpression = expression.substring(openIndex + 1, closeIndex);
            boolean innerResult = evaluateBooleanExpression(innerExpression, data);
            expression = expression.substring(0, openIndex) + innerResult + expression.substring(closeIndex + 1);
        }

        String[] orSegments = expression.split(" OR ");
        for(String orSegment : orSegments) {
            if (evaluateAndSegment(orSegment.trim())) {
                return true;
            }
        }
        return false;
    }
    private static boolean evaluateAndSegment(String expression) {
        String[] andSegments = expression.split(" AND ");
        for(String andSegment : andSegments) {
            if (!evaluateCondition(andSegment.trim())) {
                return false;
            }
        }
        return true;
    }

    private static boolean evaluateCondition(String condition) {
        String[] parts = condition.split("=");
        if(parts.length != 2) {
            return false;
        }

        String left = parts[0].trim();
        String right = parts[1].trim();

        return left.equals(right);
    }
}
